// ==UserScript==
// @name           wiki-analysis
// @namespace      http://marlink.dyndns.org:5000/
// @description    Wikipedia Revision Analysis Integrator
// @include        http://en.wikipedia.org/wiki/*
// ==/UserScript==

// get the page id
var re = new RegExp("var wgArticleId = \"(.*?)\";");
var m = re.exec(document.documentElement.innerHTML)
var page_id = m[1]

// make a switch form
function make_form() {
    if (document.getElementById("formElem") != null) return
    var sn = document.getElementById("siteNotice")
    
    form = "<form action='' style='float:right; font-size:85%;";
    form += "background-color:#F5F5F5; border:1px solid #AAA; margin-top:1.1em; padding:0px .5em;'><div>";
    form += "<label id='wikilabel'>Original</label>";
    form += "<input type='radio' id='wiki' checked='checked' name='coloring'/>";
    form += "<label id='agelabel' style='padding-left:1em;'>Persistent / New</label>";
    form += "<input type='radio' id='age' name='coloring'/>";
    form += "<label id='controlabel' style='padding-left:1em;'>Consistency / Controversy</label>";
    form += "<input type='radio' id='contro' name='coloring'/>";
    form += "<label id='greylabel' style='padding-left:1em;'>Added / Removed</label>";
    form += "<input type='radio' id='grey' name='coloring'/>";
    form += "</div></form>";
    
    // insert the form
    var formElem = document.createElement("formElem")
    formElem.innerHTML = form
    sn.parentNode.insertBefore(formElem, sn)
    
    // add event listeners
    wiki = document.getElementById("wiki");
    wiki.addEventListener("click", switch_wiki, true);
    age = document.getElementById("age");
    age.addEventListener("click", switch_age, true);
    contro = document.getElementById("contro");
    contro.addEventListener("click", switch_contro, true);
    grey = document.getElementById("grey");
    grey.addEventListener("click", switch_grey, true);
}

// event handler functions
function switch_wiki() { generateContent('wiki'); }
function switch_age() { generateContent('age'); }
function switch_contro() { generateContent('contro'); }
function switch_grey() { generateContent('grey'); }

// unicode handling
function encode_utf8( s ) { return unescape( encodeURIComponent( s ) ); }
function decode_utf8( s ) { return decodeURIComponent( escape( s ) ); }

// caching
/*var cache_test = GM_getValue(page_id + "color","")
if (cache_test != "") {
    GM_setValue(page_id + "color","wiki")
    make_form()
} else {*/

// get the delimited data
GM_xmlhttpRequest({
    method: 'GET',
    url: 'http://marlink.dyndns.org:5000/delimited/' + page_id,
    headers: {
        'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
        'Accept': 'application/atom+xml,application/xml,text/xml',
    },
    onload: function(responseDetails) {

        // check if there is data
        if (responseDetails.status == "404") return
        
        // save wiki content
        var bc = document.getElementById("bodyContent")
        GM_setValue(page_id + "wiki", encode_utf8(bc.innerHTML));
        
        // split the data        
        var delimited = responseDetails.responseText;
        p = delimited.split('\n')
        
        // make the form
        make_form()
        
        // save the data
        GM_setValue(page_id + "color","wiki")
        GM_setValue(page_id + "w",encode_utf8(p[0]))
        GM_setValue(page_id + "add",p[1])
        GM_setValue(page_id + "old",p[2])
        GM_setValue(page_id + "non",p[3])
    }
});

// helper function to convert digit to hex
function d2h(d) {
    d = parseInt(d);
    s = d.toString(16);
    if (s.length == 1) return '0' + s;
    return s;
}

// generate color
function generateContent(current_color) {
    // check if its already the current color
    if (GM_getValue(page_id + "color","") == current_color) return;
    GM_setValue(page_id + "color",current_color)

    // highlight selected
    var age_black = "Persistent / New"
    var contro_black = "Consistency / Controversy"
    var grey_black = "Added / Removed"
    
    var age_selected = "<span style='background-color:#DDFFFF;'>Persistent</span> / <span style='background-color:#FFFFDD;'>New</span>"
    var contro_selected = "<span style='background-color:#DDEEFF;'>Consistency</span> / <span style='background-color:#FFEEDD;'>Controversy</span></label>"
    var grey_selected = "<span style='background-color:#DDFFDD;'>Added</span> / <span style='background-color:#FFDDDD;'>Removed</span>"
    
    var label1 = age_black
    var label2 = contro_black
    var label3 = grey_black
    
    if (current_color == 'age') label1 = age_selected;
    else if (current_color == 'contro') label2 = contro_selected;
    else if (current_color == 'grey') label3 = grey_selected;
    document.getElementById('agelabel').innerHTML = label1;
    document.getElementById('controlabel').innerHTML = label2;
    document.getElementById('greylabel').innerHTML = label3;

    // set the body content to the original content
    if (current_color == 'wiki') {
        var bc = document.getElementById("bodyContent")
        var wiki_content = decode_utf8(GM_getValue(page_id + "wiki",""))
        bc.innerHTML = wiki_content;
        return
    }

    // load the data
    words = decode_utf8(GM_getValue(page_id + "w","")).split('\t')
    add_conf = GM_getValue(page_id + "add","").split('\t')
    old_conf = GM_getValue(page_id + "old","").split('\t')
    non_conf = GM_getValue(page_id + "non","").split('\t')
    var content = "<h3 id='siteSub'>From Wikipedia, the free encyclopedia -- processed by <a href='http://marlink.dyndns.org:5000'>Wikipedia Revision Analysis</a></h3><div id='contentSub'></div>"

    j = 0;
    for (i=0; i < words.length; i++) {
        word = words[i];
        
        if (word[0] == '<') {
            content += word;
            continue
        }
        
        add = parseFloat(add_conf[j]);
        old = parseFloat(old_conf[j]);
        non = parseFloat(non_conf[j]);
        j += 1
        
        if (current_color == "grey") {
            
            r = 255
            g = 255
            b = 255
            
            neg = 1 - add;
            pos = add;
            
            if (neg > pos) {
                g = 255 - (neg-pos) * 50;
                b = g;
            } else {
                r = 255 - (pos-neg) * 30;
                b = r;
            };
            
        } else if (current_color == "age") {
            r = 255
            g = 255
            b = 255
            
            neg = 1 - old;
            pos = old;
            
            if (neg > pos) {
                b = 255 - (neg-pos) * 50;
            } else {
                r = 255 - (pos-neg) * 30;
            }
            
        
        } else if (current_color == "contro") {
            r = 255
            g = 255
            b = 255
            
            neg = 1 - non;
            pos = non;
            
            if (neg > pos) {
                b = 255 - (neg-pos) * 30;
                g = 255 - (neg-pos) * 15;
            } else {
                r = 255 - (pos-neg) * 30;
                g = 255 - (pos-neg) * 15;
            }
            
            
        }
        
        color = d2h(r) + d2h(g) + d2h(b);
        highlight = "<span style=\"background-color:#" + color + ";\">";    
        content += highlight + word + " </span>";
    }
    if (content == '') content = '<p>&nbsp;</p>';
    
    // set the content
    var bc = document.getElementById("bodyContent")
    bc.innerHTML = content
}
